package com.atguigu04.threadsafemore.lock;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Window extends Thread {

    static int tickets = 100;

    //1.使用lock锁,必须为同一把锁
    private static final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                //2. 执行lock()方法，锁定对共享资源的调用
                lock.lock();
                if(tickets > 0 ) {

                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + ":" + tickets);
                    tickets--;
                } else {
                    break;
                }
            } finally {
                //3. unlock()的调用，释放对共享数据的锁定
                lock.unlock();
            }

        }
    }
}

public class LockTest {
    public static void main(String[] args) {


        Window window1 = new Window();
        Window window2 = new Window();
        Window window3 = new Window();

        window1.start();
        window2.start();
        window3.start();

    }
}
